package com.ptu.spzx.user.service.impl;

import com.ptu.spzx.user.service.SmsService;
import com.ptu.utils.HttpUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class SmsServiceImpl implements SmsService {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Override
    public void sendCode(String phone) {
        String code = redisTemplate.opsForValue().get(phone);
        if(StringUtils.hasText(code)){
            return;
        }

        //1 生成验证码
        code = RandomStringUtils.randomNumeric(4);
        //2 把生成的验证码放到redis里面去，设置过期时间
        redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
        //3 向手机号发送短信
        sendMessage(phone,code);
    }
    //发送短信验证码的方法
    private void sendMessage(String phone, String code) {
        String host = "https://cxkjsms.market.alicloudapi.com";
        String path = "/chuangxinsms/dxjk";
        String method = "POST";
        String appcode = "08fa962716854a73a320fa4d192daf61";//开通服务后 买家中心-查看AppCode
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("content", "【创信】你的验证码是："+code+"，5分钟内有效！");
        querys.put("mobile", phone);
        Map<String, String> bodys = new HashMap<String, String>();


        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
